<% layout('layout/appLayout') %>
<% block('header').append(`<style>
.weui-navbar + .weui-tab__bd {
    padding-top: 40px;
}
.whblock{
    background:#FFF;
    margin-bottom:10px;
    padding:10px;
    font-size:14px;
}
.wh_line + .wh_line{
   margin-top:7px;
   padding-top:7px;
   border-top:1px solid #e3e3e3;
}
.page__ft.fixed{
   position: fixed;
    width: 100%;
    bottom: 0px;
    background: #FFF;
    height: 41px;
    border-top: 1px solid #e3e3e3;
}
.weui-dialog.postage_detail {
    width:94%;
}
.weui-dialog.postage_detail .weui-dialog__bd {
        padding: 0 10px 10px;
    height: 356px;
    max-height: 356px;
    overflow: hidden;
}
ul.traces_ul {
    margin: 0;
    padding: 0;
    list-style: none;
}
ul.traces_ul li {
    font-size: 12px;
    text-align: left;
    padding-bottom: 5px;
    border-bottom: 1px solid #f0f0f0;
    padding-top: 5px;
}
</style>`)%>
<div class="page has_head" style="height:100%;">
  <div class="page__hd weui-flex">
    <div style="width:60px;padding-left:10px;">
      <a href="javascript:;" onclick="history.back()"><i class="iconfont icon-back"></i>返回</a>
    </div>
    <div class="weui-flex__item">
      <h1 class="title"><%=title %></h1>
    </div>
    <div style="width:60px;"></div>
  </div>
  <div id="orders" class="page__bd" style="height:100%;">
    <div class="weui-tab">
      <div class="weui-navbar">
        <a class="weui-navbar__item <%=!query.posi || (query.posi && query.posi ==='all')?' weui-bar__item--on ':'' %>" style="padding: 8px 0;"  data-type="all" href="#tab1">全部</a>
        <a class="weui-navbar__item <%=query.posi && query.posi ==='waitPay'?' weui-bar__item--on ':'' %>" style="padding: 8px 0;"  data-type="waitPay"  href="#tab2">待付款</a>
        <a class="weui-navbar__item <%=query.posi && query.posi ==='pay'?' weui-bar__item--on ':'' %>" style="padding: 8px 0;"  data-type="pay" href="#tab3">待发货</a>
        <a class="weui-navbar__item <%=query.posi && query.posi ==='ship'?' weui-bar__item--on ':'' %>" style="padding: 8px 0;" data-type="ship" href="#tab4">已发货</a>
        <a class="weui-navbar__item <%=query.posi && query.posi ==='back'?' weui-bar__item--on ':'' %>" style="padding: 8px 0;" data-type="back" href="#tab5">已完成</a>
      </div>
      <div class="weui-tab__bd">
        <div id="tab1" class="weui-tab__bd-item infinite <%=!query.posi || (query.posi && query.posi ==='all')?'  weui-tab__bd-item--active':'' %> ">
          <div class="tab-content">

          </div>
          <div class="weui-loadmore">
            <i class="weui-loading"></i>
            <span class="weui-loadmore__tips">正在加载</span>
          </div>
        </div>
        <div id="tab2" class="weui-tab__bd-item infinite  <%=query.posi && query.posi ==='waitPay'?' weui-tab__bd-item--active':'' %>">
          <div class="tab-content">

          </div>
          <div class="weui-loadmore">
            <i class="weui-loading"></i>
            <span class="weui-loadmore__tips">正在加载</span>
          </div>
        </div>
        <div id="tab3" class="weui-tab__bd-item infinite <%=query.posi && query.posi ==='pay'?' weui-tab__bd-item--active':'' %>">
          <div class="tab-content">
          </div>
          <div class="weui-loadmore">
            <i class="weui-loading"></i>
            <span class="weui-loadmore__tips">正在加载</span>
          </div>
        </div>
        <div id="tab4" class="weui-tab__bd-item infinite <%=query.posi && query.posi ==='ship'?' weui-tab__bd-item--active':'' %>">
          <div class="tab-content">
          </div>
          <div class="weui-loadmore">
            <i class="weui-loading"></i>
            <span class="weui-loadmore__tips">正在加载</span>
          </div>
        </div>
        <div id="tab5" class="weui-tab__bd-item infinite <%=query.posi && query.posi ==='back'?' weui-tab__bd-item--active':'' %>">
          <div class="tab-content">
          </div>
          <div class="weui-loadmore">
            <i class="weui-loading"></i>
            <span class="weui-loadmore__tips">正在加载</span>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div id="orderDetail" class="weui-popup__container" style="z-index:500">
    <div class="weui-popup__overlay"></div>
    <div class="weui-popup__modal">
      <div class="toolbar">
        <div class="toolbar-inner">
          <a href="javascript:;" class="picker-button close-popup" style="left:0;right:auto;color: inherit;"><i class="iconfont icon-back"></i>返回</a>
          <h1 class="title">订单详情</h1>
        </div>
      </div>
      <div  class="modal-content" style="padding-bottom:40px;"></div>
    </div>
  </div>
</div>
<% block('footer').append(`<script id="orderDetailTpl" type="text/template" >
<div id="orderDetailWrap" >
  <div class="whblock">
    <div>下单时间：<@=order.create_at_ago @></div>
    <div>订单编号：<@=order.orderId @></div>
  </div>
  <div class="whblock no-padding">
    <div class="weui-panel weui-panel_access">
      <div class="weui-panel__hd">
        商品
        <span class="float_right <@=order.statusColor @>"><@= order.statusName @>
        <@ if(order.refunding===2){ @>
        <span  class="fs12 text-muted">[申请退款中]</span>
        <@ } @>
        </span>
      </div>
      <div class="weui-panel__bd">
        <@ order.goods.forEach(function(item){ @>
        <div class="weui-media-box weui-media-box_appmsg">
          <div class="weui-media-box__hd">
            <img class="weui-media-box__thumb" src="<@=item.imgTmb @>" alt="">
          </div>
          <div class="weui-media-box__bd">
            <h4 class="weui-media-box__title fs14" style="height:40px;"><@= item.name @></h4>
            <p class="weui-media-box__desc">单价：￥<@=item.sellPrice @></p>
          </div>
          <div class="weui-media-box__ft" style="height:60px;">
            <p class="">X<@=item.num @></p>
            <p><@= item.subPrice @></p>
          </div>
        </div>
        <@ }) @>
      </div>
    </div>
  </div>
  <div class="whblock ">
    <div class="wh_line">
      <p><@=order.address.name @> <span class="padding-left15"><@=order.address.mobile @></span></p>
      <p class="text-muted"><@=order.address.place @></p>
    </div>
    <div class="wh_line" >
      <p>商品总数：<@= order.totalNum @></p>
      <p>商品合计：￥<@=order.totalPrice @></p>
      <p>运费:￥<@=order.feePrice @></p>
    </div>
    <div class="wh_line">
      <p class="weui-cell_warn">应付：￥<@=order.needPrice @></p>
      <@ if(order.orderStatus >= 20) { @>
      <p class="main-color">实付：￥<@=order.realPrice @></p>
      <@ } @>
    </div>
  </div>
   <div class="page__ft fixed">
    <div class="weui-flex text-right padding15-h" style="padding-top:5px;">
      <div class="weui-flex__item"></div>
      <div class="status_txt padding5-h <@=order.statusColor @>"><@= order.statusName @></div>
          <@ if(order.orderStatus === 10 ){ @>
          <div id="noPayBtn" class="no_pay_btn">
            <span><a id="cancel"  href="/account/orderCancel/<@=order._id @>" class="weui-btn weui-btn_mini weui-btn_default">取消订单</a></span>
            <span><a id="toPay"  data-id="<@=order._id @>" href="javascript:void(0)"  class="weui-btn weui-btn_mini weui-btn_primary">立即付款</a></span>
          </div>
          <@ } @>
      <@ if(order.orderStatus === 20) { @>
          <div class="no_pay_btn">
            <span><a id="applyBackAmt"   data-id="<@=order._id @>" <@=order.refunding===2?'disabled':'' @> href="javascript:void(0)"  class="weui-btn weui-btn_mini weui-btn_default">
            <@=order.refunding===2?'申请退款中':'申请退款' @>
            </a></span>
          </div>
      <@ }@>
      <@ if(order.orderStatus >= 30) { @>
      <!---查看物流信息接口--->
          <@ if(order.postageId) { @>
          <div id="postageBtn">
            <span><a id="queryPostage"  data-id="<@=order.postageId @>"  href="javascript:void(0);" class="weui-btn weui-btn_mini weui-btn_default">查询物流信息</a></span>
          </div>
          <@ } @>
     <@ } @>
    </div>
    </div>
</div>
</script>`) %>
<% block('footer').append(`<script id="queryPostageTpl" type="text/template">
<div style="height:100%; overflow: auto;">
  <ul class="traces_ul">
  <@ Traces.forEach(function (item) { @>
  <li><@=item.AcceptStation @></li>
  <@ }) @>
</ul>
 <@ if(Traces.length === 0) { @>
    <p class="text-muted">快递单号：<@= LogisticCode @></p>
    <@= Reason @>
 <@ } @>
</div>
</script>`) %>
<% block('footer').append(`<script id="orderItemTpl" type="text/template" >
<@ orders.forEach(function(item){ @>
<div class="weui-panel weui-panel_access">
  <div class="weui-panel__hd weui-flex">
    <div>订单：<@=item.orderId @></div>
    <div class="weui-flex__item padding-left15"> 数量:<@=item.totalNum @></div>
    <div class="<@=item.statusColor @>"><@=item.statusName @></div>
  </div>
  <div class="weui-panel__bd">
    <a data-id="<@=item._id @>" href="javascript:void(0);" class="weui-media-box weui-media-box_appmsg">
     <@ _.each(item.goods, function(sub) { @>
      <div class="weui-media-box__hd">
        <img class="weui-media-box__thumb" src="<@=sub.imgTmb @>" alt="">
      </div>
     <@ })@>
    </a>
  </div>
</div>
<@ }) @>
</script>`) %>
<% block('footer').append(`<script>
jQuery(function(){
	var currType = 'all'
  var $orderDetail = $('#orderDetail')
  var orderDetailCompile = _.template($('#orderDetailTpl')[0].innerHTML)
  var $orders = $('#orders')
  $orders.on('click','.weui-media-box',function(){
  	var $this = $(this)
    var id = $this.data('id')
    $.get('/app/orderDetail?id='+id).done(function(res){
      var order = res.data.order
      $orderDetail.find('.modal-content').empty().append(orderDetailCompile({order:order}))
      $orderDetail.popup()
    })
  })
  var orderItemCompile = _.template($('#orderItemTpl')[0].innerHTML)
  $('.weui-navbar a').on('click',function(e) {
 	   var href = $(e.target).attr('href')
 	   currType = $(e.target).data('type')
 	   var $tabA = $(href)
 	   var $curr = $tabA.find('.tab-content')
 	   $curr.loading = false
 	   $curr.data('stop', false)
 	   // var page = $curr.data('page') || 1
 	   var page = 1
 	   getData($curr,page)
  })

  function loading ($curr) {
    $curr.next('.weui-loadmore').removeClass('weui-loadmore_line').find('.weui-loading').show().next().text('加载数据中')
  }
  function loadingStop ($curr) {
    $curr.next('.weui-loadmore')
    .addClass('weui-loadmore_line').
    find('.weui-loading')
    .hide().next().text('没有更多数据！')
  }
  function getData($curr,page, cb) {
  	if( parseInt(page) === 1) {
  		$curr.empty()
  		loading($curr)
  	}
  	$curr.data('page',page)
    $.post('/account/orderManage', {page:page, orderType: currType}).done(function(res) {
      var resData = res.data
      console.log(resData.orders.length, '-----------')
      if (resData.orders.length < 10){
      	loadingStop($curr)
      	$curr.data('stop', true)
        // $curr.next('.weui-loadmore').addClass('weui-loadmore_line').find('.weui-loading').hide().next().text('没有更多数据！')
      }
      $curr.append(orderItemCompile({orders:resData.orders}))
      cb && cb()
    })
  }
  function initPage() {
    var href =  $('.weui-bar__item--on').attr('href')
    currType= $('.weui-bar__item--on').data('type')
    var $tabA = $(href)
    var $curr = $tabA.find('.tab-content')
    var page = $curr.data('page') || 1
    console.log($curr,page)
    getData($curr,page)
  }
  initPage()
  $(".infinite").infinite().on("infinite", function() {
    var self = this;
    var $self = $(self)
    if(self.loading) return;
    self.loading = true;
    var $curr = $self.find('.tab-content')
    console.log(true, '------')
    console.log($curr.data('stop'))
    if($curr.data('stop') === true) {
      return loadingStop($curr)
    }
    console.log('我执行了没有？？')
    loading($curr)
    getData($curr,parseInt($curr.data('page'))+1, function() {
      self.loading = false
    })
  });

  $orderDetail.on('click','#cancel', function(e){
  	e.preventDefault()
  	var $this = $(this)
  	var $noPayBtn = $('#noPayBtn')
  	var $orderDetailWrap = $('#orderDetailWrap')
  	$.confirm('你确定要取消订单么','提示', function(){
      $.post($this.attr('href')).done(function(res){
      	$noPayBtn.hide()
        $orderDetailWrap.find('.status_txt').text('已取消')
      })
  	})
  	return false
  })
  var isPay = false
  $orderDetail.on('click', '#toPay', function(e){
  	e.preventDefault()
  	if(isPay) return false
  	var $this = $(this)
  	var id = $this.data('id')
  	$this.text('支付中...')
  	isPay = true
    $.post('/app/orderPayById',{id: id}).done(function(res){
      var obj = res.data
      console.log(obj)
      wxPayReady(function() {
        WeixinJSBridge.invoke('getBrandWCPayRequest', {
          "appId":obj.appId,
          "timeStamp":obj.timeStamp,
          "nonceStr":obj.nonceStr,
          "package":obj.package,
          "signType": obj.signType,
          "paySign": obj.paySign
        },
        function(res){
          isPay = false
          $this.text('立即付款')
          if(res.err_msg == "get_brand_wcpay_request:ok" ) {
            location.href='/app/paySucc?id=' + id
          } else {
            $.toast('支付已取消', 'cancel')
          }
        })
      })
      return false
    })
  })
  function wxPayReady (cb) {
    if (typeof WeixinJSBridge == 'undefined') {
      document.addEventListener('WeixinJSBridgeReady', cb, false)
    } else {
      cb()
    }
  }

  // 申请退款
  $orderDetail.on('click', '#applyBackAmt', function (e) {
  	e.preventDefault()
  	var $this = $(this)
    $.confirm('<span class="weui-cell_warn">你确定要申请退款么？</span><p class="text-muted">退款到帐时间在退款申请提交后的1～3个工作日内完成，请耐心等待</p>','提示', function(res){
      $.post('/account/applyBackAmt/' + $this.data('id')).done(res => {
      	$this.prop('disabled',true)
      	$this.text('申请退款中')
        $.alert('<p class="text-success status_txt">' + res.message + '</p>')
      })
    })
    return false
  })

  // 物流信息
  var tplComplie = _.template($('#queryPostageTpl')[0].innerHTML)
  $orderDetail.on('click', '#queryPostage', function () {
  	var $this = $(this)
  	$.toast('正在查询中...', 'text')
  	$.post('/queryPostage/' + $this.data('id')).done(res=> {
  		console.log(res)
  		$.modal({
          title: "物流信息",
          text: tplComplie(res.data.postage),
          class: 'postage_detail',
          buttons:[
            {
              text: "确定",
              className: "default",
              onClick: function(){
                  $.closeModal()
              }
            },
          ]
        });
  	}).fail(err => {
  	  console.log(err)
  	})
  })
})
</script>`)%>